{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.neural_network import MLPClassifier\n",
    "from sklearn.datasets import fetch_openml\n",
    "import numpy as np\n",
    "\n",
    "mnist = fetch_openml('mnist_784')\n",
    "X, y = mnist['data'], mnist['target']\n",
    "X_train = np.array(X[:60000], dtype=float)\n",
    "y_train = np.array(y[:60000], dtype=float)\n",
    "X_test = np.array(X[60000:], dtype=float)\n",
    "y_test = np.array(y[60000:], dtype=float)\n",
    "\n",
    "\n",
    "clf = MLPClassifier(alpha=1e-5,\n",
    "                    hidden_layer_sizes=(15,15), random_state=1)\n",
    "\n",
    "clf.fit(X_train, y_train)\n",
    "\n",
    "\n",
    "score = clf.score(X_test, y_test)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.7791"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "score"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "参数意义：\n",
    "\n",
    "hidden_layer_sizes :隐藏层大小，(50,50)表示有两层隐藏层，第一层隐藏层有50个神经元，第二层也有50个神经元。\n",
    "\n",
    "activation :激活函数,{‘identity’, ‘logistic’, ‘tanh’, ‘relu’}, 默认为relu\n",
    "\n",
    "solver： 权重优化器，{‘lbfgs’, ‘sgd’, ‘adam’}, 默认adam\n",
    "\n",
    "learning_rate_int:double,可选，默认0.001，初始学习率，控制更新权重的补偿，只有当solver=’sgd’ 或’adam’时使用。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "from pathlib import Path\n",
    "curr_path = str(Path().absolute()) \n",
    "parent_path = str(Path().absolute().parent) \n",
    "sys.path.append(parent_path) \n",
    "\n",
    "# 添加目录到系统路径方便导入模块，该项目的根目录为\".../machine-learning-toy-code\"\n",
    "from pathlib import Path\n",
    "from torch.utils.data import DataLoader\n",
    "from torchvision import datasets\n",
    "import torchvision\n",
    "import torchvision.transforms as transforms\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.metrics import classification_report\n",
    "import numpy as np\n",
    "\n",
    "\n",
    "curr_path = str(Path().absolute())\n",
    "parent_path = str(Path().absolute().parent)\n",
    "p_parent_path = str(Path().absolute().parent.parent)\n",
    "sys.path.append(p_parent_path) \n",
    "print(f\"主目录为：{p_parent_path}\")\n",
    "\n",
    "\n",
    "train_dataset = datasets.MNIST(root = p_parent_path+'/datasets/', train = True,transform = transforms.ToTensor(), download = False)\n",
    "test_dataset = datasets.MNIST(root = p_parent_path+'/datasets/', train = False, \n",
    "                               transform = transforms.ToTensor(), download = False)\n",
    "\n",
    "batch_size = len(train_dataset)\n",
    "train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)\n",
    "test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True)\n",
    "X_train,y_train = next(iter(train_loader))\n",
    "X_test,y_test = next(iter(test_loader))\n",
    "# 打印前100张图片\n",
    "images, labels= X_train[:100], y_train[:100] \n",
    "# 使用images生成宽度为10张图的网格大小\n",
    "img = torchvision.utils.make_grid(images, nrow=10)\n",
    "# cv2.imshow()的格式是(size1,size1,channels),而img的格式是(channels,size1,size1),\n",
    "# 所以需要使用.transpose()转换，将颜色通道数放至第三维\n",
    "img = img.numpy().transpose(1,2,0)\n",
    "print(images.shape)\n",
    "print(labels.reshape(10,10))\n",
    "print(img.shape)\n",
    "plt.imshow(img)\n",
    "plt.show()\n",
    "\n",
    "X_train,y_train = X_train.cpu().numpy(),y_train.cpu().numpy() # tensor转为array形式)\n",
    "X_test,y_test = X_test.cpu().numpy(),y_test.cpu().numpy() # tensor转为array形式)\n",
    "\n",
    "X_train = X_train.reshape(X_train.shape[0],784)\n",
    "X_test = X_test.reshape(X_test.shape[0],784)\n",
    "\n",
    "# solver：即使用的优化器，lbfgs：拟牛顿法， sag：随机梯度下降\n",
    "model = LogisticRegression(solver='lbfgs', max_iter=400) # lbfgs：拟牛顿法\n",
    "model.fit(X_train, y_train)\n",
    "y_pred = model.predict(X_test)\n",
    "print(classification_report(y_test, y_pred)) # 打印报告\n",
    "\n",
    "ones_col=[[1] for i in range(len(X_train))] # 生成全为1的二维嵌套列表，即[[1],[1],...,[1]]\n",
    "X_train = np.append(X_train,ones_col,axis=1)\n",
    "x_train = np.mat(X_train)\n",
    "X_test = np.append(X_test,ones_col,axis=1)\n",
    "x_test = np.mat(X_test)\n",
    "# Mnsit有0-9十个标记，由于是二分类任务，所以可以将标记0的作为1，其余为0用于识别是否为0的任务\n",
    "y_train=np.array([1 if y_train[i]==1 else 0 for i in range(len(y_train))])\n",
    "y_test=np.array([1 if y_test[i]==1 else 0 for i in range(len(y_test))])\n",
    "\n",
    "# solver：即使用的优化器，lbfgs：拟牛顿法， sag：随机梯度下降\n",
    "model = LogisticRegression(solver='lbfgs', max_iter=100) # lbfgs：拟牛顿法\n",
    "model.fit(X_train, y_train)\n",
    "y_pred = model.predict(X_test)\n",
    "print(classification_report(y_test, y_pred)) # 打印报告"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "47dfafb046f9703cd15ca753999a7e7c95274099825c7bcc45b473d6496cd1b0"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
